/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * 
 * Author: James Harpe
 * 
 * Description: This class contains the fragment which displays a user's checkout information. 
 */

package us.in.lib.acpl.Mobile_ACPL;

import java.util.ArrayList;
import java.util.List;

import com.google.analytics.tracking.android.EasyTracker;


import us.in.lib.acpl.Mobile_ACPL.adapters.CheckoutListAdapter;
import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.patron.Checkout;
import us.in.lib.acpl.Mobile_ACPL.ws.AccountInfoHandler;
import us.in.lib.acpl.Mobile_ACPL.ws.RenewalHandler;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class AccountCheckoutsFragment extends ListFragment {

	private AccountCheckoutsFragment thisFragment = this; // A reference to this
															// object
	private boolean selected[] = new boolean[0]; // Maintains the status of the
													// checkboxes in the list of
													// checkouts.
	private boolean noCheckouts = false; // Indicates whether the user has any
											// items currently checked out.

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// Inflate the fragment's layout
		RelativeLayout fragView = (RelativeLayout) inflater.inflate(
				R.layout.account_checkouts, container, false);

		// Set listeners for the button and checkbox in the bottom bar
		fragView.findViewById(R.id.renewButton).setOnClickListener(
				new ButtonListener());
		fragView.findViewById(R.id.checkoutsSelectAllBox).setOnClickListener(
				new CheckBoxListener());

		// If the user has not checkouts, make the noCheckouts TextView visible
		if (noCheckouts) {
			fragView.findViewById(R.id.noCheckouts).setVisibility(View.VISIBLE);
		}
		return fragView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Set the listener for the list of checkouts
		this.getListView().setOnItemClickListener(new ListListener());
	}

	// Called by the AccountActivity activity once account info has been
	// retrieved
	public void setList() {
		if (this.getListAdapter() == null) {

			// Get a reference to the AccountInfoHandler stored in
			// AccountActivity
			AccountActivity act = (AccountActivity) getActivity();
			AccountInfoHandler handler = act.getAccHandler();
			
			List<Checkout> checkouts = handler.getCheckouts();
			
			selected = new boolean[checkouts.size()];

			// Set the ListView adapter to contain the list of Checkout objects
			this.setListAdapter(new CheckoutListAdapter(this.getActivity(),
					checkouts, selected));

			if (checkouts.size() == 0) {
				View v = getActivity().findViewById(R.id.noCheckouts);

				this.noCheckouts = true;
				if (v != null) {
					v.setVisibility(View.VISIBLE);
				}
			}
		} else {
			CheckoutListAdapter ad = (CheckoutListAdapter) this
					.getListAdapter();
			for (int i = 0; i < selected.length; i++) {
				selected[i] = false;
			}
			ad.notifyDataSetChanged();

		}
	}

	// Called by RenewalHandler upon completion of renewal task
	public void handleRenewalResult(String[] values) {
		// show dialog
		getActivity().findViewById(R.id.accountBar).setVisibility(View.GONE);
		String text = "\n"+ values[0] + " item(s) renewed.";
		int failed = Integer.parseInt(values[1]);
		
		if (failed > 0) {
			text += "\n"
					+ failed
					+ " item(s) were not renewed.\n\nThe following items were not renewed:\n\n"
					+ values[2];
	
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
		builder.setTitle("Renewal");
		builder.setMessage(text);
		builder.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				arg0.dismiss();
			}
			
		});
		builder.create().show();
		
		
		
//		Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
//		if (failed > 0) {
//			text += "\n"
//					+ failed
//					+ " item(s) were not renewed.\n\nThe following items were not renewed:\n\n"
//					+ values[2];
//			toast.setDuration(Toast.LENGTH_LONG);
//		}
//		toast.setText(text);
//		toast.setGravity(Gravity.CENTER, 0, 0);
//		toast.show();
		
		
		
		for (int i = 0; i < selected.length; i++) {
			selected[i] = false;
		}

		CheckBox c = (CheckBox) this.getView().findViewById(
				R.id.checkoutsSelectAllBox);
		c.setChecked(false);
		CheckoutListAdapter ad = (CheckoutListAdapter) this.getListAdapter();
		ad.notifyDataSetChanged();

	}

	private class ButtonListener implements OnClickListener {

		@Override
		public void onClick(View view) {

		
			AccountActivity act = (AccountActivity) getActivity();
			act.findViewById(R.id.accountBar).setVisibility(View.VISIBLE);
			RenewalHandler handler = new RenewalHandler(thisFragment);
			ArrayList<Checkout> toRenew = new ArrayList<Checkout>();

			for (int i = 0; i < selected.length; i++) {
				if (selected[i]) {
					toRenew.add(act.getAccHandler().getCheckouts().get(i));
				}
			}
			handler.renew(toRenew);

			EasyTracker.getTracker().sendEvent("Renewal", "Renewal Button Pressed", null,null);
		}

	}

	private class CheckBoxListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			CheckBox c = (CheckBox) arg0;
			boolean checked = c.isChecked();
			for (int i = 0; i < selected.length; i++) {
				if (checked) {
			
					selected[i] = true;
				} else {
					selected[i] = false;
				}
				CheckoutListAdapter ad = (CheckoutListAdapter) getListAdapter();
				ad.notifyDataSetChanged();
			}
		}

	}

	private class ListListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> viewGroup, View view,
				int position, long id) {

			CheckBox c = (CheckBox) view.findViewById(R.id.selectForRenewalBox);
			boolean checked = c.isChecked();
			if (checked) {
				c.setChecked(false);
				selected[position] = false;
			} else {
				c.setChecked(true);
				selected[position] = true;
			}

		}

	}
	
}
